import { login, getUserInfo } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(), // 设置token初始状态  token持久化=>放到缓存中
    name: '',
    group: '',
    signature: '',
    avatar: '',
    roles: {
      menus: [],
      points: []
    }
  }
}
// 数据
const state = getDefaultState()

// 修改
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 请求中拿到roles权限点数据，通过获取用户资料data赋值给mutations传给vuex实现数据共享
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },

  // 删除缓存
  removeToken(state) {
    state.token = null// 删除缓存
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = { ...userInfo }// 使用浅拷贝赋值对象
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {

  // 用户登录
  LoginByUsername({ commit }, userInfo) {
    const username = userInfo.username.trim()
    console.log(username) // 拿到用户名
    return new Promise((resolve, reject) => {
      login({
        username: username,
        password: userInfo.password
      }).then(response => {
        const { data } = response
        // console.log(response)
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve(data)
        // getUserInfo() // 引入获取用户资料
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户资料
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo(state.token).then(response => {
        const { data } = response
        console.log(data)

        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        // 读取的字段可能不一致
        console.log(data)
        const { name, avatar, roles } = data
        // 设置给state
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_ROLES', roles)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出操作
  logout(context) { // 简单登出操作
    // 1.移除token
    context.commit('removeToken')

    // 2.清除用户信息
    context.commit('removeUserInfo')
    // 3.重置路由
    resetRouter()
    // 4.重置菜单
    context.commit('permission/setRoutes', [], { root: true })
    location.reload()
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

